//
//  HomeVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/13.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Moya
import RxSwift
import SwiftyJSON

class HomeVC: BaseVC {
  
    fileprivate var layoutModel: HomeLayoutModel?
    fileprivate var layoutCancle: Cancellable?
    fileprivate var oldNetworkState: Bool = true
    fileprivate var vcs: [UIViewController] = []

    fileprivate var isOrder = false
    fileprivate var isApply = false
    fileprivate var isInspection = false
    fileprivate var isReadingMeter = false
    
    fileprivate var placeholderView: NoDataV?

    fileprivate lazy var refuseView: RefuseAccessNetworkView = {
        let view = RefuseAccessNetworkView()
        return view
    }()


    fileprivate lazy var notConnectedV: NoNetworkView = {
        let view = NoNetworkView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 44))
        return view
    }()

    fileprivate var ant: SJAnt?

    fileprivate var acceptedOrderVC = AcceptedOrderVC()
    fileprivate var todayInspectionVC = TodayInspectionVC()
    fileprivate var myCheckVC = FlowListVC()
    fileprivate var readingMeterVC = ReadingMeterTaskViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        blueNavigationBackgroud()
        
        create()

        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(noNetworkAction), name: Notification.Name.network.networkChangeHomeShow, object: nil)
        
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(logoutAction), name: Notification.Name.updateHome.updateHomeToDefaultWhenLogout, object: nil)
        
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(refreshWorkOderAction), name: Notification.Name.updateHome.updateHomeOrderData, object: nil)
        
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(refreshInspectionAction), name: Notification.Name.updateHome.updateHomeInspectionData, object: nil)

        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(refreshMeterAction), name: Notification.Name.updateHome.updateHomeMeterData, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(change), name: NSNotification.Name.changeCompany.changeCompanyUpdateData, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(offLineUpdate), name: NSNotification.Name.offLine.updateReadingTask, object: nil)
        
        
        
        
        // app第一次进入,判断是否开启网络权限
        SJApp.onFirstStart {
            if !SJApp.isAlowNetWork {
                self.navigationController?.view.addSubview(refuseView)
            }
        }
    }
  
    
    @objc fileprivate func offLineUpdate() {
        self.readingMeterVC.updateData(by: true)
    }
    
    @objc fileprivate func change() {
        //社区切换更新数据
        self.acceptedOrderVC.updateData(by: true)
        self.todayInspectionVC.updateData(by: true)
        self.myCheckVC.updateData()
        self.readingMeterVC.updateData(by: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        GlobalConfig.baiduStatisticsPageViewStart("工作")
        if Account.isLogin {
            pullData()
        }
    }
  
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        layoutCancle?.cancel()
        GlobalConfig.baiduStatisticsPageViewEnd("工作")
    }
  
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    // 没有数据处理
    override func placeholderViewLayout() {
        let frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: view.sj.height)
        placeholderView = NoDataV(frame: frame)
        placeholderView?.topTipText = "太好啦~"
        placeholderView?.bottomTipText = "老板没有安排工作!"
        placeholderView?.image = UIImage(named: "bg-01")!
        view.addSubview(placeholderView!)
    }
    
  
    deinit {
        GlobalConfig.notificationCenter.removeObserver(self)
    }
  
}

// MARK: - action

extension HomeVC {
  
    @objc fileprivate func refreshWorkOderAction(_ noti: Notification?) {
        if isOrder {
            ant?.selected(index: 0)
            
            if noti != nil {
                if let userInfo = noti?.userInfo as? [String: Any] {
                    
                    let pData = userInfo["pushData"] as? [String: String]
                    
                    let id = pData?["workOrderId"] ?? ""
                    
                    let status = pData?["workOrderStatus"] ?? ""
                    
                    if status == "UNTREATED" || navigationController!.viewControllers.count > 1 {//待接不跳
                        return
                    }
                    
                    let vc = OrderDetailBaseVC()
                    vc.orderId = id
                    vc.parentVC = self
                    
                    vc.orderStatus = OrderHelper.getType(status: status)
                    vc.refreshBeforeClosure = {[weak self] in
                        self?.SJAntIndexChange(index: 0)
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                    
                    
                }
            }
            
        }
        else {
            pullData()
        }
    }
    
    @objc fileprivate func refreshInspectionAction() {
        if isInspection {
            todayInspectionVC.updateData(by: false)
        }
        else {
            pullData()
        }
    }
    
    @objc fileprivate func refreshMeterAction() {
        if isReadingMeter {
            ant?.selected(index: vcs.count-1)
        }
        else {
            pullData()
        }
    }
    
    @objc fileprivate func popMenuAction() {
        let popView = SJPopMenu(frame: CGRect(x: 0, y: 0, width: 150, height: 185))
        popView.delegate = self
        let temps: [(String, String)] = [("新建工单", "home_neworder_black"),
                                         ("申请流程", "home_newflow_black"),
                                         ("添加仪表", "添加仪表-黑")]
        popView.datas = temps
        popView.show(at: CGPoint(x: UIScreen.main.bounds.width - 155, y: 64))
    }
    
    // 退出登录后更新界面到默认
    @objc fileprivate func logoutAction() {
        ant?.removeFromSuperview()
        placeholderView?.removeFromSuperview()
        
        // 退出登录后 状态初始化
        self.isApply = false
        self.isOrder = false
        self.isInspection = false
    }
  
    // 新建工单
    @objc fileprivate func addOrderAction() {
        let vc = NewOrderVC()
        vc.refreshBefore = {
            self.refreshWorkOderAction(nil)
        }
        navigationController?.pushViewController(vc, animated: true)
    }
  
    @objc fileprivate func qrCodeAction() {
        
        
        
        
        
        let vc = GlobalConfig.qrCodeController { (qrCode) in
            
            
            
            let result = JSON(parseJSON: qrCode)
            let type = result["type"].stringValue
            
            //之前返回的是一个字符("123")，并非json字符，v2.0.0后返回json
            guard type.isEmpty else {
                
                if type == "meter" {//抄表
                    let vc = ReadingMeterDetailVC()
                    if result["taskId"].stringValue.isEmpty {
                        vc.meterId = result["id"].stringValue
                    }else {
                        vc.taskId = result["taskId"].stringValue
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                
                return
            }
            //之前返回的是一个字符，并非json字符
            if qrCode.sj.isNumber() {
                let vc = WriteInspectionVC()
                vc.regionNumber = qrCode
                vc.parentVC = self
                vc.isFromFunc = false
                self.navigationController?.pushViewController(vc, animated: true)
                return
            }

            if qrCode.sj.isURL() {
                let webVC = WebViewController(url: URL(string: qrCode)!)
                self.navigationController?.pushViewController(webVC, animated: true)
                return
            }

            let resultVC = ScanResultVC()
            resultVC.result = qrCode
            self.navigationController?.pushViewController(resultVC, animated: true)
        }

        self.navigationController?.pushViewController(vc, animated: true)
    }
  
}

// MARK: - SJPopMenuDelegate

extension HomeVC: SJPopMenuDelegate {
  func popMenuDidSelect(index: Int) {
    switch index {
    case 0: addOrderAction()
    case 1:
      let vc = FlowVC()
      navigationController?.pushViewController(vc, animated: true)
    case 2:
        //qrCodeAction()
        let vc = AddMeterViewController()
        navigationController?.pushViewController(vc, animated: true)
    default: break
    }
  }
}

// MARK: - fileprivate

extension HomeVC {
  
    @objc fileprivate func pullData() {
        
        if !Account.isLogin { return }
        layoutCancle?.cancel()
        SJApp.showStateBarHUD()
        self.layoutCancle = WorkorderRequest.shared.getHomeLayout { (data) in
            if let _ = self.refuseView.superview {
                self.refuseView.removeFromSuperview()
            }
            self.layoutModel = data
            
            // 如果状态和以前不一样,刷新界面
            if !(self.isOrder == data.order
                && self.isApply == data.apply
                && self.isInspection == data.inspection
                && self.isReadingMeter == data.readingMeter
                ) {
                self.updateLayout(data.isData)
            }
            
            if !data.isData {
                self.ant?.removeFromSuperview()
                self.placeholderViewLayout()
            }
        
            self.isOrder = data.order
            self.isApply = data.apply
            self.isInspection = data.inspection
            self.isReadingMeter = data.readingMeter//
        }
    }
  
  fileprivate func create() {
    view.backgroundColor = GlobalConfig.BGWhiteColor
    
    let item = UIBarButtonItem.init(image: UIImage.init(named: "home_add_white")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(popMenuAction))
    
    let scanItem = UIBarButtonItem.init(image: UIImage.init(named: "scan-white")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(popScanAction))
    //scanItem.imageInsets = UIEdgeInsets(top: scanItem.imageInsets.top, left: -11, bottom: scanItem.imageInsets.bottom, right: 11)
    scanItem.width = -11
    
    self.navigationItem.rightBarButtonItems = [item,scanItem]
    
    let menuItem = UIBarButtonItem.init(image: UIImage.init(named: "nav-menu-icon")?.withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(profileNext))
    self.navigationItem.leftBarButtonItem = menuItem
    
    acceptedOrderVC.title = "服务工单"
    acceptedOrderVC.parentVC = self
    
    todayInspectionVC.title = "今日巡检"
    todayInspectionVC.parentVC = self
    
    myCheckVC.title = "待审流程"
    myCheckVC.parentVC = self
    myCheckVC.type = .home
    
    readingMeterVC.title = "抄表任务"
    readingMeterVC.isFunction = false
    readingMeterVC.parantVC = self
    
    refuseView.refreshClosure = { [unowned self] in
        self.pullData()
    }
  }
  
    
    @objc fileprivate func popScanAction () {
        qrCodeAction()
    }
    
    //MAKR:布局
    @objc fileprivate func updateLayout(_ isData: Bool = true) {
        // 没有数据,移除内容视图,加入占位视图
        if !isData { return }
            // 有数据,移除占位视图,加入内容视图
    
        placeholderView?.removeFromSuperview()
        
        vcs.removeAll()
        if layoutModel!.order { vcs.append(acceptedOrderVC) }
        else { }
        
        if layoutModel!.apply { vcs.append(myCheckVC) }
        
        if layoutModel!.inspection { vcs.append(todayInspectionVC) }
        
        if layoutModel!.readingMeter { vcs.append(readingMeterVC) }
        
        //
        let antFrame = CGRect(x: 0, y: 0, width: UIScreen.width, height: view.bounds.height-UIScreen.tabBarHeight)
        var style = SJAntBarTitleStyle()
        
        if 1 == vcs.count { style.isAddSlider = false }
        
        if ant != nil  {//
            ant = nil
        }
        
        ant = SJAnt(frame: antFrame, VCs: vcs, parentVC: self, barStyle: style, delegate: self)
        ant?.backgroundColor = UIColor.white
       
        view.addSubview(ant!)
  }
    @objc fileprivate func profileNext() {
        let vc = ProfileVC()
        navigationController?.pushViewController(vc, animated: true)
    }
    @objc fileprivate func noNetworkAction() {
        if let _ = refuseView.superview {
            refuseView.removeFromSuperview()
        }
    }
    
//  @objc fileprivate func noNetworkAction() {
//    if !SJApp.isAlowNetWork { return }
//    
//    // 如果有网
//    if SJApp.isNetWork {
//        // ant恢复原位
//      ant?.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noBarHeight)
//        // 移除没有网的视图
//      if let _ = notConnectedV.superview {
//        notConnectedV.removeFromSuperview()
//      }
//      
//        // 如果是从没网->有网,刷新界面
//      if !oldNetworkState {
//        pullData()
//      }
//    }
//    // 如果没网
//    else {
//      // 让ant下移
//      ant?.frame = CGRect(x: 0, y: 44, width: UIScreen.width, height: UIScreen.noBarHeight)
//        // 提示没有网络出现
//      if let _ = notConnectedV.superview { }
//      else {
//        view.addSubview(notConnectedV)
//      }
//    }
//    
//    oldNetworkState = SJApp.isNetWork
//  }
  
}

extension HomeVC: SJAntDelegate {
  func SJAntIndexChange(index: Int) {
    if index > vcs.count { return }
    
    if vcs[index] is AcceptedOrderVC {
      acceptedOrderVC.updateData(by: false)
    }
    else if vcs[index] is TodayInspectionVC {
      todayInspectionVC.updateData(by: false)
    }
    else if vcs[index] is FlowListVC {
      myCheckVC.updateData()
    }
    else if vcs[index] is ReadingMeterTaskViewController {
        //readingMeterVC.updateData()
    }
  }
}









